package com.supergzt.interceptor;

import com.supergzt.context.SecurityContextHolder;
import com.supergzt.utils.MyReflectionUtils;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MybatisPlusLogicInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		ParameterHandler parameterHandler = statementHandler.getParameterHandler();
		MappedStatement ms = (MappedStatement) MyReflectionUtils.getFieldValue(parameterHandler, "mappedStatement");
		if (ms.getSqlCommandType() == SqlCommandType.SELECT && SecurityContextHolder.getLoginUser() != null) {
			BoundSql boundSql = statementHandler.getBoundSql();
			String sql = boundSql.getSql();
			Long userId = SecurityContextHolder.getUserId();
			if(sql.contains("WHERE")){
				sql = sql.replace("WHERE", "WHERE user_id = " + userId + " AND");
			}else{
				sql = sql + "WHERE user_id = " + userId;
			}
			MyReflectionUtils.setFieldValue(boundSql, "sql", sql);
		}
		return invocation.proceed();
	}
}
